/*
 * Copyright Notice ====================================================
 * This file contains proprietary information of Hewlett-Packard Co.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2013 All rights reserved. =============================
 */

package com.hp.ecs.xqa.util;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class NekoUtil {
	public static <T> List<T> parase(final String html, final Extractor<T> extractor, boolean nested) {
		DOMParser parser = new DOMParser();
		try {
			final String trim = html.replaceAll("\\>\\s+\\<", "><");
			InputSource in=new InputSource(new ByteArrayInputStream(trim.getBytes("UTF-8")));
			parser.parse(in);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
		List<T> list = new ArrayList();
		found(parser.getDocument(), list, extractor, nested);
		return list;
	}

	private static void found(Node node, List list, Extractor extractor, boolean nested) {
		Object o = extractor.extract(node);
		if (o != null) {
			list.add(o);
			if (!nested) {
				return;
			}
		}
		Node child = node.getFirstChild();
		while (child != null) {
			found(child, list, extractor, nested);
			child = child.getNextSibling();
		}
	}

	public interface Extractor<T> {
		T extract(Node node);
	}
}
